package com.example.recordingpen_datacollection.filter.token;


import com.alibaba.fastjson.JSONObject;
import com.example.recordingpen_datacollection.redisService.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class MyFilter implements Filter {

//    @Resource //作用和@Autowired，只是他按名字注入，而@Autowired按类型注入
//    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private RedisService redisService;

    private String[] excludedUrls;


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("-----------------过滤器初始化----------------");
        String excludedUrlsString = filterConfig.getInitParameter("excludedUrls");
        if (excludedUrlsString != null) {
            excludedUrls = excludedUrlsString.split(",");
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
       //校验用户登录状态
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestUrl = request.getRequestURI();

        if(request.getRequestURI().equals("/")||
                request.getRequestURI().contains("csrf")||
                request.getRequestURI().contains("swagger-")||
                request.getRequestURI().contains("api-docs")||
                request.getRequestURI().contains("api-docs")||
                request.getRequestURI().contains("favicon")){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        System.out.println(request.getRequestURI()+" --->>");
        if (excludedUrls != null) {
            for (String excludedUrl : excludedUrls) {
                if (requestUrl.startsWith(excludedUrl)) {
                    filterChain.doFilter(request, response);
                    return;
                }
            }
        }

        System.out.println("执行过滤器");
        //取出token
        String token = request.getHeader("token");
        //第一次登录没有token，给null会报错，所以我们判断一下token是否为空，为空给一个空串
        //三元运算
        token = token==null?"":token;
        //查询Redis中token的剩余时间
        Long expire = redisService.getTokenDate(token);
//        Long expire =redisTemplate.getExpire(token);
        if(expire > 0){
            //时间大于0 放行
            /*
            有一个问题，用户一直在网页上操作，但是token一直在倒计时，操作着操作着就变未登录了
            不合理，所以，当用户在操作时，每次经过过滤器调用不同接口时，就重置一下token的时间
             */
//            redisTemplate.expire("token",1L, TimeUnit.MINUTES);
            //放行
            filterChain.doFilter(servletRequest,servletResponse);
        }else {
            System.out.println("未登录！");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            JSONObject res = new JSONObject();
            res.put("success", "false");
            res.put("code", "602");
            res.put("message", "无效token");
            PrintWriter out = response.getWriter();
            out.write(res.toString());
            out.flush();
            out.close();
        }
    }

    @Override
    public void destroy() {
        System.out.println("过滤器已经死亡！");
    }
}